//
//  FQJumpAction.m
//  KDFDApp
//
//  Created by Bruce on 2017/8/30.
//  Copyright © 2017年 cailiang. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "FQJumpAction.h"
#import "FQSimpleWKWebVC.h"
#import "NSString+URL.h"
#import "FQWKWebResponseEntity.h"
#import "FQBaseWKWebViewEntity.h"

static NSString *schemeKey = @"qunajie";
@interface FQJumpAction ()
@property (nonatomic, strong) NSMutableDictionary <NSString *, void(^)(FQWKWebResponseEntity *)>*map;
@property (nonatomic, strong) NSDictionary <NSString *, Class >*classMap;
@property (nonatomic, strong) WKWebView *webView;
@end

@implementation FQJumpAction
-(NSDictionary<NSString *,void (^)(FQWKWebResponseEntity *)> *)map
{
    if (!_map) {
        _map = [@{} mutableCopy];
    }
    return _map;
}
- (NSDictionary<NSString *,Class> *)classMap
{
    if (!_classMap) {
        _classMap = @{
                      @"openweb":[FQSimpleWKWebVC class],
                      };
    }
    return _classMap;
}
-(void)action:(QCWKWebViewJSRequestEntity *)requestEntity andCallbackBlock:(void (^)(FQWKWebResponseEntity *))response
{
    if (requestEntity&&requestEntity.callback) {
        [self.map setObject:[response copy] forKey:requestEntity.callback];
    }
    [self jump:requestEntity];
}
- (void)setWebView:(WKWebView *)webview
{
    _webView = webview;
}
#pragma mark - 链接分割 取出路径&参数(供非action类使用)
+ (NSMutableDictionary *)rsolve:(NSString *)urlString
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSString *host = url.host;
    NSString *scheme = [url.scheme stringByAppendingString:@"://"];
    
    //scheme不正确 直接报错返回
    if (![scheme isEqualToString:[NSString stringWithFormat:@"%@://",schemeKey]]&&![scheme isEqualToString:@"scheme://"]&&![scheme isEqualToString:@"http://"]&&![scheme isEqualToString:@"https://"]) {
        return nil;
    }
    //host不正确 直接报错返回
    if (!host) {
        return nil;
    }
    NSMutableArray *array = [[urlString componentsSeparatedByString:scheme] mutableCopy];
    if ([array containsObject:@""]) {
        [array removeObject:@""];
    }
    //通过scheme截取的数组在去空之后个数为0 链接有误报错返回
    if (array.count == 0) {
        return nil;
    }
    //通过host切割数组
    NSString *separatorSring = array[0];
    NSMutableArray *paramArray = [[separatorSring componentsSeparatedByString:@"app.launch/"] mutableCopy];
    [paramArray removeObject:@""];
    if (paramArray.count == 0) {
        return nil;
    }
    //得到最终 path+params字符串
    NSString *pathParamString = paramArray[0];
    NSMutableDictionary *finalDic = [@{} mutableCopy];
    if ([pathParamString rangeOfString:@"?"].location == NSNotFound) {
        [finalDic setValue:pathParamString forKey:@"path"];
        return finalDic;
    }
    
    NSMutableArray *finalArray = [[pathParamString componentsSeparatedByString:@"?"] mutableCopy];
    [finalArray removeObject:@""];
    if (finalArray.count == 0) {
        [finalDic setValue:pathParamString forKey:@"path"];
        return finalDic;
    }
    NSString *path = finalArray[0];
    
    NSMutableDictionary *paramDic = [pathParamString getURLParameters];
    [finalDic setValue:path forKey:@"path"];
    if (paramDic) {
        [finalDic setValue:paramDic forKey:@"param"];
    }
    return  finalDic;
    
}
#pragma mark - 根据参数开始跳转页面（jumpaction内部使用）
- (void)jump:(QCWKWebViewJSRequestEntity *)request{
    BOOL browser = [self jumpBrowser:request];
    //如果是打开外部浏览器 return
    if (browser) {
        return;
    }
    //如果是http请求直接跳转
    if ([self jumpHttpURL:request andParamUrl:nil isPush:false]) {
        return;
    }
    
    NSMutableDictionary *dic =  [self resolveURL:request];
    if (!dic) {
        return;
    }
    NSString *path = dic[@"path"];    
    if (!path) {
        [self illegalHandle:request errorCode:ENUM_NOMethod errorMessage:@"path缺失，iOS客户端不支持该URL！"];
    }
    id class = self.classMap[path];
    if (!class) {
        [self illegalHandle:request errorCode:ENUM_NOMethod errorMessage:@"path不存在，iOS客户端不支持该URL！"];
        return;
    }
    //开始跳转
    [self jumpNew:dic entity:request isPush:false];
}


- (BOOL)needLoginStatus:(NSString *)path {
    //不需要登录态的scheme
    NSArray *schemeArray = [NSArray arrayWithObjects:@"main",
                            @"login/applogin",
                            @"login/forgetpwd",
                            @"me",
                            @"find",
                            @"circle",
                            @"openweb",
                            @"saoyisao",
                            @"service",
                            @"specialProduct",
                            @"search",
                            @"WeChatMiniProgram",
                            @"tool",
                            @"webCircle",
                            @"moreCircle",
                            @"wechatPublicAccount",nil];
    if ([schemeArray containsObject:path]) {
        return NO;
    }
    return YES;
}

- (void)jumpNew:(NSMutableDictionary *)dic entity:(QCWKWebViewJSRequestEntity *)request isPush:(BOOL)isPush{
    NSString *path = dic[@"path"];
    id class = self.classMap[path];
    if (!class) {
        return;
    }
    
    [self jumpAction:dic entity:request isPush:isPush];
}

#pragma mark - 在配置中查找path是否存在及参数
- (void)jumpAction:(NSMutableDictionary *)dic entity:(QCWKWebViewJSRequestEntity *)request isPush:(BOOL)isPush {
    NSString *path = dic[@"path"];
    NSDictionary *param = dic[@"param"];
    
    id class = self.classMap[path];
    if (!class) {
        return;
    }
    if (class == [FQSimpleWKWebVC class]){
        [self jumpHttpURL:request andParamUrl:param[@"url"] isPush:isPush];
    }
    else{
        Class myclass = (Class)class;
        UIViewController *instance= [[myclass alloc]init];
//        [[FQTabBarController shareTabController]pushToViewController:instance];
        [self handleSucceedCallback:request];
    }
}

- (NSMutableDictionary *)resolveURL:(QCWKWebViewJSRequestEntity *)request
{
    NSString *urlString = [NSString stringWithFormat:@"%@",request.params[@"url"]];
    NSURL *url = [NSURL URLWithString:urlString];
    NSString *host = url.host;
    NSString *scheme = [url.scheme stringByAppendingString:@"://"];
    
    //scheme不正确 直接报错返回
    if (![scheme isEqualToString:[NSString stringWithFormat:@"%@://",schemeKey]]&&![scheme isEqualToString:@"scheme://"]&&![scheme isEqualToString:@"http://"]&&![scheme isEqualToString:@"https://"]) {
        [self illegalHandle:request errorCode:ENUM_NOMethod errorMessage:@"scheme有误，iOS客户端不支持该scheme！"];
        return nil;
    }
    //host不正确 直接报错返回
    if (!host) {
        [self illegalHandle:request errorCode:ENUM_NOMethod errorMessage:@"host有误，iOS客户端不支持该host！"];
        return nil;
    }
    NSMutableArray *array = [[urlString componentsSeparatedByString:scheme] mutableCopy];
    if ([array containsObject:@""]) {
        [array removeObject:@""];
    }
    //通过scheme截取的数组在去空之后个数为0 链接有误报错返回
    if (array.count == 0) {
        [self illegalHandle:request errorCode:ENUM_NOMethod errorMessage:@"path缺失，iOS客户端不支持该URL！"];
        return nil;
    }
    //通过host切割数组
    NSString *separatorSring = array[0];
    NSMutableArray *paramArray = [[separatorSring componentsSeparatedByString:@"app.launch/"] mutableCopy];
    [paramArray removeObject:@""];
    if (paramArray.count == 0) {
        [self illegalHandle:request errorCode:ENUM_NOMethod errorMessage:@"参数缺失，iOS客户端不支持该URL！"];
        return nil;
    }
    //得到最终 path+params字符串
    NSString *pathParamString = paramArray[0];
    NSMutableDictionary *finalDic = [@{} mutableCopy];
    if ([pathParamString rangeOfString:@"?"].location == NSNotFound) {
        [finalDic setValue:pathParamString forKey:@"path"];
        return finalDic;
    }
    
    NSMutableArray *finalArray = [[pathParamString componentsSeparatedByString:@"?"] mutableCopy];
    [finalArray removeObject:@""];
    if (finalArray.count == 0) {
        [finalDic setValue:pathParamString forKey:@"path"];
        return finalDic;
    }
    NSString *path = finalArray[0];
    
    NSMutableDictionary *paramDic = [pathParamString getURLParameters];
    [finalDic setValue:path forKey:@"path"];
    if (paramDic) {
        [finalDic setValue:paramDic forKey:@"param"];
    }
    return  finalDic;
}
#pragma mark - 非法URL处理
- (void)illegalHandle:(QCWKWebViewJSRequestEntity *)request errorCode:(Code)code errorMessage:(NSString *)errorMessage{
    FQWKWebResponseEntity *response = [FQWKWebResponseEntity getResponse];
    response.callbackid = request.callback;
    response.data.code = code;
    response.data.message = errorMessage;
    [self.map enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, void (^ _Nonnull obj)(FQWKWebResponseEntity *response), BOOL * _Nonnull stop) {
        if (key == request.callback) {
            obj(response);
        }
    }];
}
#pragma mark - 跳转成功处理
- (void)handleSucceedCallback:(QCWKWebViewJSRequestEntity *)request{
    if (!request) {
        return;
    }
    FQWKWebResponseEntity *response = [FQWKWebResponseEntity getResponse];
    response.callbackid = request.callback;
    response.data.code = ENUM_Succeed;
    response.data.message = @"succeed";
    [self.map enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, void (^ _Nonnull obj)(FQWKWebResponseEntity *response), BOOL * _Nonnull stop) {
        if (key == request.callback) {
            obj(response);
        }
    }];
}

#pragma mark - 跳转外部浏览器
- (BOOL)jumpBrowser:(QCWKWebViewJSRequestEntity *)request{
    NSString *is_browser = [NSString stringWithFormat:@"%@",request.params[@"is_browser"]];
    if (is_browser&&[is_browser integerValue] == 1) {
        UIApplication *application = [UIApplication sharedApplication];
        NSURL *URL = [NSURL URLWithString:request.params[@"url"]];
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [application openURL:URL options:@{}
               completionHandler:^(BOOL success) {
                   if (success) {
                       [self handleSucceedCallback:request];
                   }else{
                       [self illegalHandle:request errorCode:ENUM_ResolveFail errorMessage:@"此链接不支持外部浏览器打开！请核查链接"];
                   }
               }];
        } else {
            BOOL success = [application openURL:URL];
            if (success) {
                [self handleSucceedCallback:request];
            }else{
                [self illegalHandle:request errorCode:ENUM_ResolveFail errorMessage:@"此链接不支持外部浏览器打开！请核查链接"];
            }
        }
        return true;
    }else
    {
        return false;
    }
}
#pragma mark - 跳转到http、https页面
- (BOOL)jumpHttpURL:(QCWKWebViewJSRequestEntity *)request andParamUrl:(NSString *)paramUrl isPush:(BOOL)isPush{
    
    NSString *urlString = paramUrl ? paramUrl : [NSString stringWithFormat:@"%@",request.params[@"url"]];
    //增加decode代码
    if (isPush) {
        urlString = [urlString stringByRemovingPercentEncoding];
    }
    //增加容错
    if (![urlString isKindOfClass:[NSString class]]||!urlString) {
        return true;
    }
    NSString *escapeUrl = urlString;
    NSURL *url = [NSURL URLWithString:escapeUrl];
    if ([url.scheme isEqualToString:@"http"]||[url.scheme isEqualToString:@"https"]) {
        UIViewController *vc = (UIViewController *)[UIApplication sharedApplication].windows[0].rootViewController;
       
        FQSimpleWKWebVC *web = [[FQSimpleWKWebVC alloc]init];
        [web loadWebURLSring:urlString];
        if ([vc isKindOfClass:[UINavigationController class]]) {
            
        }
        return  true;
    }
    return false;
}

@end
